package com.jzo2o.orders.manager.handler;

import cn.hutool.core.collection.CollUtil;
import com.jzo2o.api.trade.RefundRecordApi;
import com.jzo2o.api.trade.dto.response.ExecutionResultResDTO;
import com.jzo2o.api.trade.enums.RefundStatusEnum;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.base.model.domain.OrdersRefund;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import com.jzo2o.orders.manager.service.IOrdersManagerService;
import com.jzo2o.orders.manager.service.IOrdersRefundService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wys
 * @version V1.0
 * @date 2025-04-05 11:22
 */
@Component
public class OrdersHandler {
    @Resource
    private IOrdersCreateService ordersCreateService;
    @Resource
    private IOrdersManagerService ordersManagerService;
    @Resource
    private IOrdersRefundService ordersRefundService;
    @Resource
    private RefundRecordApi refundRecordApi;
    @Resource
    private OrdersHandler owner;

    @XxlJob(value = "cancelOverTimePayOrder")
    public void cancelOverTimePayOrder() {
        // 查询支付超时状态订单
        List<Orders> ordersList = ordersCreateService.queryOverTimePayOrdersListByCount(100);
        if (CollUtil.isEmpty(ordersList)) {
            XxlJobHelper.log("查询超时订单列表为空！");
            return;
        }
        ordersList.forEach(v -> {
            OrderCancelDTO orderCancelDTO = new OrderCancelDTO();
            orderCancelDTO.setId(v.getId());
            orderCancelDTO.setCurrentUserName("SYSTEM");
            orderCancelDTO.setCurrentUserType(UserType.SYSTEM);
            orderCancelDTO.setCancelReason("订单超时,自动取消");
            ordersManagerService.cancelByNoPay(orderCancelDTO);
        });
    }

    /**
     * 订单退款异步任务
     */
    @XxlJob(value = "handleRefundOrders")
    public void handleRefundOrders() {
        // 查询退款中订单
        List<OrdersRefund> ordersRefundList = ordersRefundService.queryRefundOrderListByCount(100);
        for (OrdersRefund ordersRefund : ordersRefundList) {
            // 请求退款
            requestRefundOrder(ordersRefund);
        }
    }

    /**
     * 请求退款
     *
     * @param ordersRefund 退款记录
     */
    public void requestRefundOrder(OrdersRefund ordersRefund) {
        ExecutionResultResDTO executionResultResDTO = refundRecordApi.refundTrading(ordersRefund.getTradingOrderNo(), ordersRefund.getRealPayAmount());
        owner.refundOrder(ordersRefund, executionResultResDTO);
    }

    /**
     * 更新退款状态
     *
     * @param ordersRefund
     * @param executionResultResDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void refundOrder(OrdersRefund ordersRefund, ExecutionResultResDTO executionResultResDTO) {
        Integer refundStatus = executionResultResDTO.getRefundStatus();
        if (ObjectUtils.equal(refundStatus, RefundStatusEnum.SENDING.getCode())) {
            return;
        }
        boolean update = ordersManagerService.lambdaUpdate().eq(Orders::getId, ordersRefund.getId())
                .ne(Orders::getRefundStatus, refundStatus)
                .set(Orders::getTradingOrderNo, ordersRefund.getTradingOrderNo())
                .set(ObjectUtils.isNotNull(executionResultResDTO.getRefundId()), Orders::getRefundId, executionResultResDTO.getRefundId())
                .set(ObjectUtils.isNotNull(executionResultResDTO.getRefundId()), Orders::getRefundNo, executionResultResDTO.getRefundNo())
                .update();
        if (update){
            ordersRefundService.removeById(ordersRefund);
        }
    }
}
